package cnpm.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import cnpm.dao.ContractDAO;
import cnpm.entity.Contract;
import cnpm.entity.Employee;
import cnpm.util.HibernateUtil;

public class ContractDAOImpl implements ContractDAO {

	private SessionFactory sessionFactory;
	private Session session;
	
	public ContractDAOImpl() {
		sessionFactory = HibernateUtil.getSessionFactory();
	}
	
	@Override
	public boolean saveOrUpdateContract(Contract c) {
		try{
			session = sessionFactory.openSession();
			session.beginTransaction();
			session.saveOrUpdate(c);
			session.beginTransaction().commit();
			return true;
		}catch(HibernateException e1){
			if(session.beginTransaction() == null){
				session.beginTransaction().rollback();
			}
			e1.printStackTrace();
		}finally{
			session.close();
		}
		return false;
	}

	@Override
	public boolean deleteContract(Contract c) {
		try{
			session = sessionFactory.openSession();
			session.beginTransaction();
			session.delete(c);
			session.beginTransaction().commit();
			return true;
		}catch(HibernateException e1){
			if(session.beginTransaction() == null){
				session.beginTransaction().rollback();
			}
			e1.printStackTrace();
		}finally{
			session.close();
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Contract> getAllContract(Employee e) {
		List<Contract> clist = null;
		try{
			session = sessionFactory.openSession();
			clist = session.createCriteria(Contract.class)
					.add(Restrictions.eq("empContract", e)).list();
			return clist;
		}catch(HibernateException e1){
			e1.printStackTrace();
		}finally{
			session.close();
		}
		return clist;
	}

	@Override
	public Contract getContractByID(String contractID) {
		try {
			session = sessionFactory.openSession();
			return (Contract) session.get(Contract.class, contractID);
		} catch (HibernateException e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
		return null;
	}
}
